package com.ruoyi.web.controller.module.estate;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.domain.module.event.EventPlanTask;
import com.ruoyi.system.service.module.event.IEventPlanTaskService;
import com.ruoyi.web.controller.common.BaseController;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDeptEventType;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.EstateUser;
import com.ruoyi.system.domain.module.product.Product;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysDeptEventTypeService;
import com.ruoyi.system.service.system.ISysDeptService;
import com.ruoyi.system.service.system.ISysUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 小区的管理用户wxuser的用户Controller
 *
 * @author ruoyi
 * @date 2022-04-27
 */
@Validated
@Api(value = "小区的管理用户wxuser的用户控制器", tags = {"小区的管理用户wxuser的用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate/user")
public class EstateUserController extends BaseController {

    private final IEstateUserService estateUserService;
	private final IWxUserService wxUserService;
	private final ISysUserService sysUserService;
	private final ISysDeptEventTypeService sysDeptEventTypeService;
	private final ISysDeptService sysDeptService;
	private final IEstateService estateService;
	private final ISysUserService userService;
	private final IEventPlanTaskService eventPlanTaskService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询小区的管理用户wxuser的用户列表
     */
    @ApiOperation("查询小区的管理用户wxuser的用户列表")
    @PreAuthorize("@ss.hasPermi('module:estateUser:list')")
    @GetMapping("/list")
    public TableDataInfo<EstateUser> list(@Validated EstateUser estateUser) {
        QueryWrapper<EstateUser> qw = new QueryWrapper<>();
        if(estateUser.getEstateId()!=null){
        	qw.eq("estate_id",estateUser.getEstateId());
		}
		if(estateUser.getNickName()!=null){
			qw.like("nick_name",estateUser.getNickName());
		}
		if(estateUser.getSysUserId()!=null){
			qw.eq("sys_user_id",estateUser.getSysUserId());
		}
		if (estateUser.getDeptId()!=null){
			if(estateUser.getDeptId() == 0){
				qw.and(wrapper->{
					wrapper.eq("dept_id","0").or().isNull("dept_id");
				});
			}else{
				qw.eq("dept_id",estateUser.getDeptId());
			}
		}
		if (estateUser.getState()!=null){
			qw.eq("state",estateUser.getState());
		}
        TableDataInfo<EstateUser> td = PageUtils.buildDataInfo(estateUserService.page(PageUtils.buildPage(),qw));
        List<EstateUser> list = td.getRows();
		if(CollUtil.isNotEmpty(list)){
			for (EstateUser merUser1 : list){
				SysUser sysUser = sysUserService.getById(merUser1.getSysUserId());
				if(sysUser!=null){
					merUser1.setSysUserName(sysUser.getUserName());
					merUser1.setSysNickName(sysUser.getNickName());
					merUser1.setPhoneNum(sysUser.getPhoneNum());
					merUser1.setSex(sysUser.getSex());
					merUser1.setRemark(sysUser.getRemark());
				}
				WxUser wxUser = wxUserService.getById(merUser1.getUserId());
				if(wxUser!=null){
					merUser1.setWxUserName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					merUser1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						merUser1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
				if (merUser1.getDeptId()!=null){
					merUser1.setDeptName(sysDeptService.getById(merUser1.getDeptId()).getDeptName());
				}
				if (merUser1.getEstateId()!=null){
					merUser1.setEstateName(estateService.getById(merUser1.getEstateId()).getEstateName());
				}
			}
		}
        return td;
    }

	@ApiOperation("查询小区的管理用户wxuser的用户列表")
	@PreAuthorize("@ss.hasPermi('module:estateUser:list')")
	@GetMapping("/listEventUser")
	public List<EstateUser> estateUserList(@Validated EstateUser estateUser) {
		SysUser sysUser = getUser();
		QueryWrapper<SysDeptEventType> sys = new QueryWrapper<>();
		if (estateUser.getEventType()!=null){
			sys.eq("event_type",estateUser.getEventType());
		}
		List<SysDeptEventType> sysDeptEventTypes = sysDeptEventTypeService.list(sys);
		List<EstateUser> users = new ArrayList<>();
		if (sysDeptEventTypes.size() > 0){
			List<Integer> deptList = new ArrayList<>();
			for (SysDeptEventType sysDeptEventType:sysDeptEventTypes){
				//判断小区是否正确
				QueryWrapper<SysDept> dept = new QueryWrapper<>();
				if(sysUser.getUserType() == 2){
					dept.eq("property_id",sysUser.getPropertyId());
					if (sysUser.getEstateId()!=null){
						dept.eq("estate_id",sysUser.getEstateId());
					}
				} else if(sysUser.getUserType() == 3){
					dept.eq("estate_id",sysUser.getEstateId());
				}
				dept.eq("dept_id",sysDeptEventType.getDeptId());
				List<SysDept> depts = sysDeptService.list(dept);
				if (depts.size()>0){
					for (SysDept dept1:depts){
						deptList.add(dept1.getDeptId());
					}
				}
			}
			for (Integer i:deptList){
				QueryWrapper<EstateUser> user = new QueryWrapper<>();
				user.eq("dept_id",i);
				user.eq("state",1);
				if (estateUser.getEstateId()!=null){
					user.eq("estate_id",estateUser.getEstateId());
				}
				List<EstateUser> estateUserList = estateUserService.list(user);
				if (estateUserList.size()>0) {
					for (EstateUser estateUser1 : estateUserList){
						users.add(estateUser1);
					}
				}
			}

		}
		return users;
	}

	/**
	 * 查询小区工作人员表列表
	 */
	@ApiOperation("查询小区工作人员表列表")
	@PreAuthorize("@ss.hasPermi('module:estateUser:list')")
	@GetMapping("/listByEstate")
	public AjaxResult listByEstate(@Validated EstateUser estateUser) {
		QueryWrapper<EstateUser> qw = new QueryWrapper<>();
		if(estateUser.getEstateId() != null){
			qw.eq("estate_id",estateUser.getEstateId());
		}
		if(estateUser.getUserType() != null){
			qw.eq("user_type",estateUser.getUserType());
		}
		if(estateUser.getIsManager() != null){
			qw.eq("is_manager",estateUser.getIsManager());
		}
		qw.eq("state",1);
		List<EstateUser> list = estateUserService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (EstateUser user : list){
				SysUser sysUser = sysUserService.selectUserById(user.getSysUserId());
				if(sysUser!= null){
					user.setSysUserName(sysUser.getUserName());
					user.setNickName(sysUser.getNickName());
					user.setPhoneNum(sysUser.getPhoneNum());
					user.setSex(sysUser.getSex());
					user.setRemark(sysUser.getRemark());
				}
			}
		}
		return AjaxResult.success(list);
	}


    /**
     * 获取小区的管理用户wxuser的用户详细信息
     */
    @ApiOperation("获取小区的管理用户wxuser的用户详细信息")
    @PreAuthorize("@ss.hasPermi('module:estateUser:query')")
    @GetMapping("/{id}")
    public AjaxResult<EstateUser> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateUser estateUser = estateUserService.getById(id);
		if(estateUser != null){
			if(estateUser.getUserId()!= null){
				WxUser wxUser = wxUserService.findById(estateUser.getUserId());
				if(wxUser != null){
					estateUser.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}
			if(estateUser.getSysUserId() != null){
				SysUser sysUser = sysUserService.selectUserById(estateUser.getSysUserId());
				if(sysUser != null){
					if (sysUser.getUserName() != null) {
						estateUser.setSysUserName(sysUser.getUserName());
					}
					if (sysUser.getNickName() != null) {
						estateUser.setSysNickName(sysUser.getNickName());
					}
					if (sysUser.getPhoneNum() != null) {
						estateUser.setPhoneNum(sysUser.getPhoneNum());
					}
					if (sysUser.getUserName() != null) {
						estateUser.setSex(sysUser.getSex());
					}
					if (sysUser.getUserName() != null) {
						estateUser.setRemark(sysUser.getRemark());
					}
				}

			}
		}
        return AjaxResult.success(estateUser);
    }

    /**
     * 新增小区的管理用户wxuser的用户
     */
//    @ApiOperation("新增小区的管理用户wxuser的用户")
//    @PreAuthorize("@ss.hasPermi('module:estateUser:add')")
//    @Log(title = "小区的管理用户wxuser的用户", businessType = BusinessType.INSERT)
//    @RepeatSubmit
//    @PostMapping()
//    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateUser estateUser) {
//    	boolean bl = false;
//    	QueryWrapper<EstateUser> qw = new QueryWrapper<>();
//    	qw.eq("estate_id",estateUser.getEstateId());
//		qw.eq("sys_user_id",estateUser.getSysUserId());
//		qw.eq("user_id",estateUser.getUserId());
//		qw.and(wrapper->{
//			wrapper.eq("user_id",0).or().isNull("user_id");
//		});
//		qw.last("limit 1");
//		qw.orderByAsc("id");
//		EstateUser user = estateUserService.getOne(qw);
//		if(user != null){
//			user.setUserId(estateUser.getUserId());
//			bl = estateUserService.updateById(user);
//			if(bl){
//				return AjaxResult.success("添加成功");
//			}else{
//				return AjaxResult.error("添加失败");
//			}
//		}else{
//			user = new EstateUser();
//			user.setEstateId(estateUser.getEstateId());
//			user.setSysUserId(estateUser.getSysUserId());
//			user.setUserId(estateUser.getUserId());
//			user.setCreateTime(new Date());
//			user.setNickName(estateUser.getNickName());
//			user.setIsManager(0);
//			user.setState(1);
//			bl = estateUserService.save(user);
//			if(bl){
//				return AjaxResult.success("添加成功");
//			}else{
//				return AjaxResult.error("添加失败");
//			}
//		}
////		return AjaxResult.success("该用户已存在");
//    }

	@ApiOperation("新增小区的管理用户wxuser的用户")
	@PreAuthorize("@ss.hasPermi('module:estateUser:add')")
	@Log(title = "小区的管理用户wxuser的用户", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping()
	public AjaxResult<Void> addUser(@Validated(AddGroup.class) @RequestBody EstateUser estateUser) {
		SysUser sysUser = new SysUser();
		sysUser.setRoleId(4);
		sysUser.setUserType(3);
		if (estateUser.getDeptId()!=null){
			sysUser.setDeptId(estateUser.getDeptId());
		}
		if (estateUser.getEstateId()!=null){
			sysUser.setEstateId(estateUser.getEstateId());
			Estate estates = estateService.findById(estateUser.getEstateId());
			if (estates!=null){
				sysUser.setPropertyId(estates.getPropertyId());
			}
		}
		if (estateUser.getSysUserName()!=null){
			if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(estateUser.getSysUserName()))) {
				return AjaxResult.error("新增用户'" + estateUser.getSysUserName() + "'失败，登录账号已存在");
			}
			sysUser.setUserName(estateUser.getSysUserName());
		}
//		sysUser.setNickName(estateUser.getSysNickName());
		if (estateUser.getNickName()!=null){
			estateUser.setNickName(estateUser.getNickName());
			sysUser.setNickName(estateUser.getNickName());
		}
		if (estateUser.getPhoneNum()!=null){
			sysUser.setPhoneNum(estateUser.getPhoneNum());
			if (Validator.isNotEmpty(estateUser.getPhoneNum())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
				return AjaxResult.error("新增用户'" + estateUser.getPhoneNum() + "'失败，手机号码已存在");
			}
		}
		sysUser.setSex(estateUser.getSex());
		sysUser.setRemark(estateUser.getRemark());

		if (estateUser.getPassword()!=null){
			sysUser.setPassword(SecurityUtils.encryptPassword(estateUser.getPassword()));
		}
		if (estateUser.getEmail()!=null){
			sysUser.setEmail(estateUser.getEmail());
		}
		if (estateUser.getSex()!=null){
			sysUser.setSex(estateUser.getSex());
		}
		userService.insertUser(sysUser);
		estateUser.setSysUserId(sysUser.getUserId());

		if(estateUser.getIsManager() == null){
			estateUser.setIsManager(0);
		}
		return toAjax(estateUserService.save(estateUser) ? 1 : 0);
	}
    /**
     * 修改小区的管理用户wxuser的用户
     */
    @ApiOperation("修改小区的管理用户wxuser的用户")
    @PreAuthorize("@ss.hasPermi('module:estateUser:edit')")
    @Log(title = "小区的管理用户wxuser的用户", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateUser estateUser) {
		if(estateUser.getIsManager() == null){
			estateUser.setIsManager(0);
		}

		if(estateUser.getSysUserId() != null){
			SysUser sysUser = sysUserService.selectUserById(estateUser.getSysUserId());
			if(sysUser != null){
				sysUser.setDeptId(estateUser.getDeptId());
				sysUser.setSex(estateUser.getSex());
				sysUser.setRemark(estateUser.getRemark());
				sysUserService.updateById(sysUser);
			}
		}

        return toAjax(estateUserService.updateById(estateUser) ? 1 : 0);
    }



	/**
	 * 修改小区的管理用户wxuser的用户
	 */
	@ApiOperation("修改小区的管理用户wxuser的用户")
	@PreAuthorize("@ss.hasPermi('module:estateUser:edit')")
	@Log(title = "小区的管理用户wxuser的用户", businessType = BusinessType.UPDATE)
	@PostMapping("/updateManager")
	public AjaxResult<Void> updateManager(@Validated(EditGroup.class) @RequestBody EstateUser estateUser) {

//		estateUserService.update(new LambdaUpdateWrapper<EstateUser>()
//			.set(EstateUser::getIsManager,0)
//			.eq(EstateUser::getEstateId,estateUser.getEstateId()));
//		estateUser.setIsManager(1);
		return toAjax(estateUserService.updateById(estateUser) ? 1 : 0);
	}



	/**
	 * 修改在职状态
	 */
	@Log(title = "修改在职状态", businessType = BusinessType.UPDATE)
	@PutMapping("/stateSaleOutStatus")
	public AjaxResult stateSaleOutStatus(@RequestBody EstateUser estateUsers) {
		EstateUser user = estateUserService.findById(estateUsers.getId());
		if (user!=null){
			user.setState(estateUsers.getState());
			//员工设置离职
			if (estateUsers.getState()==0){
				//eventTask设置为已删除状态
				QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
				qwTask.eq("worker_sys_user_id",user.getSysUserId());
				qwTask.eq("state",0);
				List<EventPlanTask> taskList = eventPlanTaskService.list(qwTask);
				for (EventPlanTask task:taskList){
					task.setState(4);
					eventPlanTaskService.updateById(task);
				}
			}
			//员工取消离职
			if (estateUsers.getState()==1){
				QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
				qwTask.eq("worker_sys_user_id",user.getSysUserId());
				qwTask.eq("state",4);
				List<EventPlanTask> taskList = eventPlanTaskService.list(qwTask);
				for (EventPlanTask task:taskList){
					task.setState(0);
					eventPlanTaskService.updateById(task);
				}
			}
		}else {
			return toAjax(0);
		}
		return toAjax(estateUserService.updateById(user));
	}


	/**
     * 删除小区的管理用户wxuser的用户
     */
    @ApiOperation("删除小区的管理用户wxuser的用户")
    @PreAuthorize("@ss.hasPermi('module:estateUser:remove')")
    @Log(title = "小区的管理用户wxuser的用户" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		boolean bl = false;
    	for (Integer id : ids){
			EstateUser estateUser = estateUserService.findById(id);
			if(estateUser!=null){
				QueryWrapper<EstateUser> qw = new QueryWrapper<>();
				qw.eq("estate_id",estateUser.getEstateId());
				qw.eq("sys_user_id",estateUser.getSysUserId());
				long count = estateUserService.count(qw);
				if(count > 1){
					bl = estateUserService.removeById(estateUser.getId());
				}else{
					estateUser.setUserId(0);
					bl = estateUserService.updateById(estateUser);
				}
				if(estateUser.getSysUserId() != null){
					SysUser sysUser = sysUserService.selectUserById(estateUser.getSysUserId());
					int p = 0;
					if(sysUser!= null){
						p = sysUserService.deleteUserById(sysUser.getUserId());
					}
					if (p==0){
						bl=false;
					}else {
						bl=true;
					}
				}
				bl = estateUserService.removeById(estateUser.getId());
			}
		}

        return toAjax(bl ? 1 : 0);
    }
}
